import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import type { ChatItem } from '@/types/chat';

// 聊天消息查询参数
interface ChatMessagesParams {
  chatId: string;
  page?: number;
  pageSize?: number;
  order?: 'asc' | 'desc';
}

// 聊天消息分页响应
interface ChatMessagesResponse {
  messages: ChatItem[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
}

// POST /api/client/chat/sessions/messages - 获取聊天会话消息列表
async function handlePost(request: NextRequest): Promise<ChatMessagesResponse> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前学生ID
  const studentId = authResult.user?.id;
  if (!studentId) {
    throw new Error('学生信息不存在');
  }

  // 3. 解析参数
  const body: ChatMessagesParams = await request.json();
  const { 
    chatId, 
    page = 1, 
    pageSize = 50, 
    order = 'asc' 
  } = body;

  if (!chatId) {
    throw new Error('聊天会话ID为必填项');
  }

  // 4. 验证会话是否属于当前学生
  const chatSession = await prisma.chatSession.findFirst({
    where: {
      chatId,
      userId: studentId,
    },
    select: {
      id: true,
      chatId: true
    }
  });

  if (!chatSession) {
    throw new Error('聊天会话不存在或无权限访问');
  }

  // 5. 计算分页参数
  const skip = (page - 1) * pageSize;

  // 6. 查询消息总数
  const total = await prisma.chatMessage.count({
    where: {
      sessionId: chatSession.id
    }
  });

  // 7. 查询消息列表
  const messages = await prisma.chatMessage.findMany({
    where: {
      sessionId: chatSession.id
    },
    select: {
      id: true,
      sessionId: true,
      role: true,
      content: true,
      createdAt: true,
      chatItemId:true
    },
    orderBy: {
      createdAt: order
    },
    skip,
    take: pageSize
  });

  // 8. 计算分页信息
  const totalPages = Math.ceil(total / pageSize);
  const hasNextPage = page < totalPages;
  const hasPrevPage = page > 1;

  // 9. 数据转换
  const formattedMessages: ChatItem[] = messages.map(msg => ({
    id: msg.id,
    chatItemId: msg.chatItemId,
    role: msg.role,
    content: msg.content,
    createdAt: msg.createdAt.toISOString()
  })) as unknown as ChatItem[];

  return {
    messages: formattedMessages,
    total,
    page,
    pageSize,
    totalPages,
    hasNextPage,
    hasPrevPage
  };
}

export const POST = withMiddleware(handlePost);
